from faker import Faker
import random
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from data_mock.utils import FileUtil, MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 配置基础数据 ==========
ADMISSION_TYPES = ['急诊入院', '门诊入院', '转院入院', '其他']
FEE_TYPES = ['医保', '自费', '公费', '商业保险', '其他']


# ========== 时间范围配置 ==========
def generate_DAY_RANGE(start_day, end_day):
    start = datetime.strptime(start_day, "%Y-%m-%d")
    end = datetime.strptime(end_day, "%Y-%m-%d")
    days = []
    current = start
    while current <= end:
        days.append(current.strftime("%Y-%m-%d"))
        current += relativedelta(days=1)
    return days


DAY_RANGE = generate_DAY_RANGE("2025-08-01", "2025-08-03")


def generate_records_per_day(day: str):
    date_obj = datetime.strptime(day, '%Y-%m-%d')
    return 8 if date_obj.day % 2 == 0 else 6


# ========== 核心生成函数 ==========
def generate_inpatient_records():
    sql_statements = []
    record_count = 0

    patient_id_counter = 1001  # 与b02_1保持一致
    visit_sn_counter = 1001

    for day in DAY_RANGE:
        RECORDS_PER_day = generate_records_per_day(day)
        for i in range(1, RECORDS_PER_day + 1):
            record_count += 1

            # 保持与b02_1相同的ID生成逻辑
            patient_id = f"PT{patient_id_counter}"
            visit_sn = f"VIS{visit_sn_counter}"
            patient_id_counter += 1
            visit_sn_counter += 1

            # 从b02_1可能继承的字段
            medical_record_no = f"MR{random.randint(100000, 999999)}"
            inpatient_no = f"IP{random.randint(100000, 999999)}"
            hospitalization_times = str(random.randint(1, 3))
            name = fake.name()

            # 住院特定字段
            admission_datetime = fake.date_time_between(
                start_date=datetime.strptime(day, "%Y-%m-%d") - timedelta(days=5),
                end_date=datetime.strptime(day, "%Y-%m-%d")
            ).strftime('%Y-%m-%d %H:%M:%S')

            fee_type = random.choice(FEE_TYPES)
            admission_type_name = random.choice(ADMISSION_TYPES)

            # 系统字段
            record_status = random.randint(0, 1)
            yy_batch_time = day
            yy_record_batch_id = f"BATCH{day}_{i}"
            yy_etl_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            data = {
                'patient_id': patient_id,
                'visit_sn': visit_sn,
                'medical_record_no': medical_record_no,
                'inpatient_no': inpatient_no,
                'hospitalization_times': hospitalization_times,
                'name': name,
                'admission_datetime': admission_datetime,
                'fee_type': fee_type,
                'admission_type_name': admission_type_name,
                'record_status': record_status,
                'yy_etl_time': yy_etl_time,
                'yy_upload_status': 0,
                'yy_upload_time': None,
                'yy_batch_time': yy_batch_time,
                'yy_record_batch_id': yy_record_batch_id,
                'yy_backfill_time': None,
                'yy_backfill_status': None
            }

            sql = _generate_sql('b03_1', data)
            sql_statements.append(sql)

    return sql_statements


def _generate_sql(table, data):
    columns = ', '.join([f'`{k}`' for k in data.keys()])
    values = []
    for v in data.values():
        if v is None:
            values.append('NULL')
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({columns}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    records = generate_inpatient_records()
    # 写入数据库
    MysqlUtils_AI.insert_data_to_hub(records, 'b03_1')
    # 或写入 SQL 文件
    # FileUtil.generate_sql_file(records, "b03_1_inpatient_records.sql")
